package com.cx.base.day19_thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @Author: robert.song
 * @Date: Created in 2021/11/26
 * @Target: ABA问题本身不影响数据安全，下面是ABA案例
 */
@Slf4j
public class Thread_13_3_原子性_时间戳原子引用_ABA处理 {
    static AtomicStampedReference<String> ref = new AtomicStampedReference<>("A", 0);

    public static void main(String[] args) throws InterruptedException {
        log.info("main start...");
//        获取值A
        String prev = ref.getReference();
        int stamp = -ref.getStamp();
        other();
        Thread.sleep(2);
//        改为C
        log.info("change A->C {}", ref.compareAndSet(prev, "C", stamp, stamp + 1));

    }

    private static void other() {
        Thread thread = new Thread(() -> {
            log.info("change A->B {}", ref.compareAndSet(ref.getReference(), "B", ref.getStamp(), ref.getStamp() + 1));
            log.info("change B->A {}", ref.compareAndSet(ref.getReference(), "A", ref.getStamp(), ref.getStamp() + 1));
        });
        thread.start();

    }
}
